<?php
/**
 * Provides resources for sending SMS messages to cell phones for whole
 * system.
 * 
 * @author Martin "DevelX" Jurča
 */
class SMSGate extends Module {
    protected $name = 'SMSGate';
    protected $administrable = true;
    protected $version = '2009-08-20';
    protected $details = array('dependencies' => array(),
            'observes' => array('SMSGate'));

    const GATES = 'smsGates';

    private $gatesTable = array('id' => 'iPN+', 'prefix' => 's', 'gate' =>
            's');

    private $gatesRecord = array('table' => self::GATES, 'data' => array());

    public function  __construct(DBAPI $dbapi, RecordList $recordList) {
        parent::__construct($dbapi, $recordList);
        $this->gatesRecord['properties'] = $this->gatesTable;
    }

    public function install() {
        Modules::getModule('Users')->registerRights($this->getName(),
                $this->getRights());
        return $this->dbdriver->createTable(self::GATES, $this->gatesTable);
    }

    public function uninstall() {
        return $this->dbdriver->dropTable(self::GATES);
    }

    public function initDisplay($param = null) {}

    public function display($param = null) {
        if (Kernel::getMode() == Kernel::ADMIN) {
            $this->displayAdmin($param);
        }
    }

    public function sendSMS($from, $fromName, $to, $message) {
        if (!$this->hasRights('send sms')) {
            Modules::getModule('View')->addMessage($this->lang(
                    'insufficentRights'), View::MSG_WARNING);
            return false;
        }
        $params = array('filter' => "'" . $this->dbdriver->escapeString($to) .
                "' LIKE CONCAT(`prefix`, '%')", 'order' =>
                array('!LENGTH(`prefix`)'), 'count' => 1);
        $gates = $this->recordList->getList($this->gatesRecord, $params);
        if (count($gates) > 0) {
            return Modules::getModule('EmailGate')->sendMail($from, $fromName,
                    "$to@" . $gates[0]['gate'], '', '', $message);
        }
        return false;
    }

    public function &onAddOperator(&$details, $source) {
        $result = null;
        if (!$this->hasRights('add operator')) {
            Modules::getModule('View')->addMessage($this->lang(
                    'insufficentRights'), View::MSG_ERROR);
            return $result;
        }
        $gate = $this->gatesRecord;
        $gate['data'] = array('prefix' => $details['prefix'], 'gate' =>
                $details['gate']);
        $this->dbapi->save($gate);
        return $result;
    }

    public function &onEditOperator(&$details, $source) {
        $result = null;
        if (!$this->hasRights('edit operator')) {
            Modules::getModule('View')->addMessage($this->lang(
                    'insufficentRights'), View::MSG_ERROR);
            return $result;
        }
        $gate = $this->gatesRecord;
        $gate['data'] = array('id' => $details['id'], 'prefix' =>
                $details['prefix'], 'gate' => $details['gate']);
        $this->dbapi->update($gate);
        return $result;
    }

    public function &onDeleteOperator(&$details, $source) {
        $result = null;
        Kernel::setRedirect($this->getLink());
        if (!$this->hasRights('delete operator')) {
            Modules::getModule('View')->addMessage($this->lang(
                    'insufficentRights'), View::MSG_ERROR);
            return $result;
        }
        $gate = $this->gatesRecord;
        $gate['data']['id'] = (int) substr($details, 0, -1);
        $this->dbapi->delete($gate);
        return $result;
    }

    public function &onSendSMS(&$details, $source) {
        $result = null;
        if (!$this->hasRights('send sms')) {
            Modules::getModule('View')->addMessage($this->lang(
                    'insufficentRights'), View::MSG_ERROR);
            return $result;
        }
        $this->sendSMS($details['from'], $details['fromName'], $details['to'],
                $details['text']);
        return $result;
    }

    /**
     * Displays module administration.
     *
     * @param mixed $param Display parameter.
     */
    private function displayAdmin($param) {
        if (!$this->hasRights('view admin')) {
            return;
        }
        if ($param == 'submenu') {
            $this->displayAdminSubmenu();
        } else {
            $details = Modules::getModule('View')->getUrl();
            if (count($details) == 2) {
                if ($details[1] == 'add-operator') {
                    $this->displayAdminAddOperator();
                } elseif ($details[1] == 'operators') {
                    $this->displayAdminOperators();
                }
            } elseif (count($details) == 3) {
                if ($details[1] == 'edit-operator') {
                    $this->displayAdminEditOperator((int) $details[2]);
                }
            } elseif (count($details) == 1) {
                $this->displayAdminSendSMS();
            }
        }
    }

    /**
     * Displays administration interface for sending new SMS.
     *
     */
    private function displayAdminSendSMS() {
        if (!$this->hasRights('send sms')) {
            return;
        }
        $params = array('formStart' => $this->getForm('sendSMS', true,
                'SMSGate'), 'sendSMSForm' => $this->lang('sendSMSForm'),
                'from' => $this->lang('from'), 'fromName' => $this->lang(
                'fromName'), 'to' => $this->lang('to'), 'text' => $this->lang(
                'text'), 'send' => $this->lang('send'));
        $this->template('sms', $params);
    }

    /**
     * Displays administration interaface for editing operator gate settings.
     *
     * @param int $id Gate ID nubmer.
     */
    private function displayAdminEditOperator($id) {
        if (!$this->hasRights('edit operator')) {
            return;
        }
        $gate = $this->gatesRecord;
        $gate['data']['id'] = (int) $id;
        $this->dbapi->refresh($gate);
        $params = array('formStart' => $this->getForm('editOperator', true,
                'SMSGate'), 'editOperatorForm' => $this->lang(
                'editOperatorForm'), 'numberPrefix' => $this->lang(
                'numberPrefix'), 'gate' => $this->lang('gate'), 'save' =>
                $this->lang('save'), 'operator' => $gate['data']);
        $this->template('edit', $params);
    }

    /**
     * Displays administration interface for listing created gates.
     *
     */
    private function displayAdminOperators() {
        $params = array();
        $gates = $this->recordList->getList($this->gatesRecord, $params);
        foreach ($gates as &$gate) {
            $gate['edit'] = $this->getLink("edit-operator/{$gate['id']}/");
            $gate['delete'] = $this->getLink("{$gate['id']}/",
                    'deleteOperator');
        }
        $params = array('operatorsTable' => $this->lang('operatorsTable'),
                'gates' => $gates, 'edit' => $this->lang('edit'), 'delete' =>
                $this->lang('delete'));
        $this->template('operators', $params);
    }

    /**
     * Displays administration interface for adding a new operator.
     *
     */
    private function displayAdminAddOperator() {
        if (!$this->hasRights('add operator')) {
            return;
        }
        $params = array('formStart' => $this->getForm('addOperator', true,
                'SMSGate'), 'addOperatorForm' => $this->lang(
                'addOperatorForm'), 'numberPrefix' => $this->lang(
                'numberPrefix'), 'gate' => $this->lang('gate'), 'create' =>
                $this->lang('create'));
        $this->template('add', $params);
    }

    /**
     * Displays module administration submenu.
     *
     */
    private function displayAdminSubmenu() {
        $params = array('menu' => array(array('href' => $this->getLink(),
                'title' => $this->lang('sendMessageTitle'), 'label' =>
                $this->lang('sendMessage')), array('href' => $this->getLink(
                'operators/'), 'title' => $this->lang('operatorsTitle'),
                'label' => $this->lang('operators')), array('href' =>
                $this->getLink('add-operator/'), 'title' => $this->lang(
                'addOperatorTitle'), 'label' => $this->lang('addOperator'))));
        $this->template('submenu', $params);
    }
}
?>
